package com.xr.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.sunnyday.constant.MessageConstant;
import com.xr.sunnyday.entity.Result;
import com.xr.sunnyday.service.MemberService;
import com.xr.sunnyday.service.ReportService;
import com.xr.sunnyday.service.SetmealService;
import com.xr.sunnyday.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        //定义一个传到前台月份的数组 String
        List<String> months = new ArrayList<>();
        //日历对象
        Calendar calendar = Calendar.getInstance();
        // 设置过去一年的时间
        calendar.add(Calendar.YEAR,-1);
        for (int i = 0;i<12;i++){
            try {
            //每次增加一个月
                calendar.add(Calendar.MONTH,1);
                //过去的日期
                Date date = calendar.getTime();
                //转成YYYY-MM-DD
                String dateString = DateUtils.parseDate2String(date);
                //添加到传到前端的数组
                months.add(dateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 调用服务查询过去12个月会员数据 前端也是一数组 数值
        List<Integer> menbercount = memberService.getMemberReport(months);

        // 放入map
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("months",months);
        resultMap.put("memberCount",menbercount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,resultMap);
    }
    /**
     * 套餐预约占比
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //调用服务查询套餐预约占比,它包含了前端页面需要的套餐名称集合
        List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();
        //2.抽取套餐名称集合
        List<String> setmealNames = new ArrayList<String>();
        for (Map<String, Object> map : setmealCount) {
            String setmealName = (String)map.get("name");
            setmealNames.add(setmealName);
        }
        //3.封装结果返回给页面
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("setmealNames",setmealNames);
        resultMap.put("setmealCount",setmealCount);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,resultMap);
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String,Object> businessReport = reportService.getBusinessReport();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReport);
    }

    /**
     * 导出运营统计数据报表
     */
    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res){
        //1.获取所有的报表的数据
        Map<String, Object> reportData = reportService.getBusinessReport();
        //获取excel模板的路径
        String template = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        // 创建工作簿(模板路径)
        try (// 写在try()里的对象，必须实现closable接口，try()cathc()中的finally
             OutputStream os = res.getOutputStream();
             XSSFWorkbook wk = new XSSFWorkbook(template);) {
            // 获取工作表
            XSSFSheet sht = wk.getSheetAt(0);
            //获取单元格并赋值
            //============日期===============
            sht.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());

            //============会员信息===============
            sht.getRow(4).getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
            sht.getRow(4).getCell(7).setCellValue((Integer)reportData.get("totalMember"));
            sht.getRow(5).getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
            sht.getRow(5).getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));

            //============预约数量===============
            sht.getRow(7).getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
            sht.getRow(7).getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
            sht.getRow(8).getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
            sht.getRow(8).getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
            sht.getRow(9).getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
            sht.getRow(9).getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

            //============热门套餐===============
            //获取热门套餐的数据
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>)reportData.get("hotSetmeal");
            //先定位到模板的12行
            int rowIndex = 12;
            for (Map<String, Object> setmeal  : hotSetmeal) {
                sht.getRow(rowIndex).getCell(4).setCellValue((String)setmeal.get("name"));
                sht.getRow(rowIndex).getCell(5).setCellValue((Long)setmeal.get("setmeal_count"));
                BigDecimal proportion = (BigDecimal)setmeal.get("proportion");
                sht.getRow(rowIndex).getCell(6).setCellValue(proportion.doubleValue());
                rowIndex++;
            }
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");
            //3.告诉浏览器，是下载文件
            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            //数据输出到文件
            wk.write(os);
            //刷新
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
